package com.neusoft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.dto.ArticleQueryCondition;
import com.neusoft.dto.ArticleReq;
import com.neusoft.mapper.*;
import com.neusoft.model.*;
import com.neusoft.service.IArticleService;
import com.neusoft.utils.UserUtils;
import com.neusoft.vo.Article;
import com.neusoft.vo.Author;
import com.neusoft.vo.MultiArticles;
import com.neusoft.vo.SingleArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    ArticlesMapper articlesMapper;
    @Autowired
    TagsMapper tagsMapper;
    @Autowired
    ArticleTagsMapper articleTagsMapper;
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    FavoriteMapper favoriteMapper;
    @Autowired
    FollowMapper followMapper;


    @Override
    public SingleArticle createArticle(ArticleReq articleReq) {

        Articles articles = new Articles();
        articles.setTitle(articleReq.getTitle());
        articles.setBody(articleReq.getBody());
        Users users = UserUtils.getLoginUser();
        articles.setAuthorId(users.getId());
        articles.setDescription(articleReq.getDescription());
        String slug = UUID.randomUUID().toString();
        articles.setSlug(slug);
        articlesMapper.insert(articles);

        process(articleReq, articles);

        return this.getArticle(articles.getSlug());
    }

    @Override
    public SingleArticle getArticle(String slug) {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(queryWrapper);
        Users currentUser = UserUtils.getLoginUser();
        QueryWrapper<Favorites> queryFavoritesWrapper = new QueryWrapper<>();
        if (currentUser != null) {
            queryFavoritesWrapper.eq("user_id", currentUser.getId())
                    .eq("article_id", articles.getId());
        } else {
            queryFavoritesWrapper.eq("user_id", 0)
                    .eq("article_id", articles.getId());
        }
        Integer count = favoriteMapper.selectCount(queryFavoritesWrapper);
        if (articles != null) {
            Article article = new Article();
            article.setSlug(articles.getSlug());
            article.setTitle(articles.getTitle());
            article.setBody(articles.getBody());
            article.setDescription(articles.getDescription());
            article.setCreatedAt(articles.getCreatedAt());
            article.setUpdatedAt(articles.getUpdatedAt());
            List<String> tagList = articlesMapper.getTagListByArticleSlug(slug);
            article.setTagList(tagList);
            //查询作者信息
            int authorId = articles.getAuthorId();
            Users users = usersMapper.selectById(authorId);
            Author author = new Author();
            author.setBio(users.getBio());
            author.setImage(users.getImage());
            author.setUsername(users.getUsername());
            QueryWrapper<Follows> queryFollowsWrapper = new QueryWrapper<>();
            if (currentUser != null) {
                queryFollowsWrapper.eq("follower_id", currentUser.getId()).eq("followee_id", authorId);
            }
            else{
                queryFollowsWrapper.eq("follower_id", 0).eq("followee_id", authorId);
            }
            Integer followCount = followMapper.selectCount(queryFollowsWrapper);
            if (followCount > 0) {
                author.setFollowing(true);
            } else {
                author.setFollowing(false);
            }

            article.setAuthor(author);
            if (count > 0) {
                article.setFavorited(true);
            } else {
                article.setFavorited(false);
            }
            //查询文章点赞数
            int articleId = articles.getId();
            int favoritesCount = articlesMapper.getFavoritesCountByArticleId(articleId);
            article.setFavoritesCount(favoritesCount);

            SingleArticle singleArticle = new SingleArticle();
            singleArticle.setArticle(article);
            return singleArticle;
        }
        return new SingleArticle();
    }

    @Override
    public SingleArticle updateArticle(String slug, ArticleReq articleReq) {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(queryWrapper);
        articles.setBody(articleReq.getBody());
        articles.setDescription(articleReq.getDescription());
        articles.setTitle(articleReq.getTitle());
        articlesMapper.updateById(articles);

        QueryWrapper<ArticleTags> queryArticleTagsWrapper = new QueryWrapper<>();
        queryArticleTagsWrapper.eq("article_id", articles.getId());
        articleTagsMapper.delete(queryArticleTagsWrapper);

        process(articleReq, articles);

        return this.getArticle(articles.getSlug());
    }

    @Override
    public MultiArticles getMultiArticles(ArticleQueryCondition articleQueryCondition) {
        MultiArticles multiArticles = new MultiArticles();
        if (articleQueryCondition.getLimit() == null) {
            articleQueryCondition.setLimit(20);
        }
        if (articleQueryCondition.getOffset() == null) {
            articleQueryCondition.setOffset(0);
        }
        Users loginUser = UserUtils.getLoginUser();
        if (loginUser != null) {
            articleQueryCondition.setCurrentLoginUserId(loginUser.getId());
        } else {
            articleQueryCondition.setCurrentLoginUserId(0);
        }
        List<Article> articles = articlesMapper.getArticles(articleQueryCondition);
        for (Article article : articles) {
            List<String> taglist = new ArrayList<>();
            if (article.getTag_arr()[0] != null) {
                taglist = Arrays.asList(article.getTag_arr());
            }
            article.setTagList(taglist);
        }
        multiArticles.setArticles(articles);
        int articleCount = articlesMapper.getArticlesCount(articleQueryCondition);
        multiArticles.setArticlesCount(articleCount);

        return multiArticles;
    }

    @Override
    public SingleArticle favoriteArticle(String slug) {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(queryWrapper);
        Users currentUser = UserUtils.getLoginUser();
        Favorites favorites = new Favorites();
        favorites.setUserId(currentUser.getId());
        favorites.setArticleId(articles.getId());
        favoriteMapper.insert(favorites);

        return this.getArticle(articles.getSlug());

    }

    @Override
    public SingleArticle unFavoriteArticle(String slug) {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(queryWrapper);
        Users currentUser = UserUtils.getLoginUser();
        Favorites favorites = new Favorites();
        favorites.setUserId(currentUser.getId());
        favorites.setArticleId(articles.getId());
        Map<String, Object> condition = new HashMap<>();
        condition.put("user_id", currentUser.getId());
        condition.put("article_id", articles.getId());

        favoriteMapper.deleteByMap(condition);
        return this.getArticle(articles.getSlug());

    }

    @Override
    public MultiArticles getMultiArticlesFeed(ArticleQueryCondition articleQueryCondition) {
        Users currentUser = UserUtils.getLoginUser();
        articleQueryCondition.setCurrentLoginUserId(currentUser.getId());
        if (articleQueryCondition.getLimit() == null) {
            articleQueryCondition.setLimit(20);
        }
        if (articleQueryCondition.getOffset() == null) {
            articleQueryCondition.setOffset(0);
        }
        List<Article> articles = articlesMapper.getArticlesFeed(articleQueryCondition);
        for (Article article : articles) {
            List<String> taglist = new ArrayList<>();
            if (article.getTag_arr()[0] != null) {
                taglist = Arrays.asList(article.getTag_arr());
            }
            article.setTagList(taglist);
        }
        MultiArticles multiArticles = new MultiArticles();
        multiArticles.setArticles(articles);
        int articleCount = articlesMapper.getArticlesFeedCount(articleQueryCondition);
        multiArticles.setArticlesCount(articleCount);
        return multiArticles;
    }


    private void process(ArticleReq articleReq, Articles articles) {
        for (String tag : articleReq.getTagList()) {
            QueryWrapper<Tags> queryTagsWrapper = new QueryWrapper<>();
            queryTagsWrapper.eq("name", tag);
            Tags tags = tagsMapper.selectOne(queryTagsWrapper);
            if (tags == null) {
                tags = new Tags();
                tags.setName(tag);
                tagsMapper.insert(tags);
            }
            ArticleTags articleTags = new ArticleTags();
            articleTags.setArticleId(articles.getId());
            articleTags.setTagId(tags.getId());
            articleTagsMapper.insert(articleTags);
        }
    }
}
